package com.lagou.edu.service.impl;

import com.lagou.edu.dao.CodeDao;
import com.lagou.edu.pojo.AuthCode;
import com.lagou.edu.service.ICodeService;
import com.lagou.edu.service.IEmailServiceFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author stevejson
 */
@Service
@Slf4j
public class CodeServiceImpl implements ICodeService {
    @Resource
    private CodeDao codeDao;

    @Resource
    private IEmailServiceFeignClient emailServiceFeignClient;

    @Override
    public boolean createCode(String email) {
        int number = (int)(Math.random()*(999999-100000+1)+100000);
        Date create=new Date();
        Date expire= new Date(create.getTime() + 60000*10);
        AuthCode code = new AuthCode();
        code.setCreateTime(create);
        code.setExpireTime(expire);
        code.setEmail(email);
        code.setCode(String.valueOf(number));
        try {
            codeDao.save(code);
        } catch (Exception e) {
            log.error("存储code异常", e);
            return false;
        }
        //发送邮件
        return emailServiceFeignClient.sendEmail(email, String.valueOf(code.getCode()));
    }

    @Override
    public int validateCode(String email, String code) {
        if(StringUtils.isBlank(email) || StringUtils.isBlank(code)){
            log.info("验证email和code不能为空"+ email+":"+code);
            return 1;
        }
        Date now = new Date();
        AuthCode lastCode = null;
        try {
            lastCode = codeDao.findLastCode(email, code);
        } catch (Exception e) {
            log.error("查询code出错",e);
            return 1;
        }
        if(null == lastCode){
            return 1;
        }
        if(lastCode.getExpireTime().before(now)){
            return 2;
        }
        return 0;
    }
}
